package context

import (
	"dag2.0/gat1400-proxy/logger"
	"github.com/spf13/viper"
	"os"
	"path"
	"strings"
	"sync"
)

const _CONFIG_PATH = "./config.yml"

var rwLock sync.RWMutex

var configMaps = make(map[string]interface{}, 0)

func init() {
	//init config
	//defaultPath := `E:\git\DAG2.0-AU\Go\src\gat1400-proxy`
	defaultPath := GetAppPath()
	logger.LOG_WARN("appPath is ", defaultPath)
	configPath := path.Join(defaultPath, _CONFIG_PATH)
	logger.LOG_INFO("configPath:", configPath)
	viper.SetConfigFile(configPath)
	viper.SetConfigType("yaml")
	if err := viper.ReadInConfig(); err != nil {
		logger.LOG_ERROR("Fail to read config file :", err)
	}
}

func Init() {

}


func GetAppPath() string {
	return os.Args[0][:(strings.LastIndex(os.Args[0], string(os.PathSeparator)) + 1)]
}

//配置
func Set(key string, value interface{}) {
	rwLock.Lock()
	viper.Set(key, value)
	rwLock.Unlock()
}

func IsExsit(key string) bool {
	return viper.IsSet(key)
}

func GetString(key string) string {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetString(key)
}
func GetStringDefault(key ,defaultValue string) string {
	rwLock.RLock()
	defer rwLock.RUnlock()
	if viper.GetString(key) == ""{
		return defaultValue
	}
	return viper.GetString(key)
}
func GetIntDefault(key string,defaultValue int)  int{
	rwLock.RLock()
	defer rwLock.RUnlock()
	if viper.GetInt(key) == 0{
		return defaultValue
	}
	return viper.GetInt(key)
}
func GetInt(key string) int {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetInt(key)
}
func GetInt32(key string) int32 {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetInt32(key)
}
func GetInt64(key string) int64 {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetInt64(key)
}
func GetFloat64(key string) float64 {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetFloat64(key)
}
func GetFloat64Default(key string,defaultValue float64)  float64{
	rwLock.RLock()
	defer rwLock.RUnlock()
	if viper.GetFloat64(key) == 0{
		return defaultValue
	}
	return viper.GetFloat64(key)
}
func GetBool(key string) bool {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetBool(key)
}

func GetStringMapString(key string) map[string]string {
	rwLock.RLock()
	defer rwLock.RUnlock()
	return viper.GetStringMapString(key)
}
